//
//  SeekBrandbaseView.m
//  cityCar
//
//  Created by yao on 14-10-29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SeekBrandbaseView.h"
#import "Connection.h"
#import "Car.h"
#import "UIImageView+WebCache.h"
#import "WebColor.h"
#import "SeekBrandDetailCell.h"
#import "MJRefresh.h"
#import "SeekBrandBaseViewCell.h"
@implementation SeekBrandbaseView

- (void)dealloc
{
    [_arrayRow release];
    [_arraySection release];
    [_array release];
    [_dictionary release];
    [_tableView release];
    [_indexBar release];
    [_stringId release];
    [_chiArrayRow release];
    [_chiArraySection release];
    [_chiDictionary release];
    [_searchArray release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.array        = [NSMutableArray array];
        self.arraySection = [NSMutableArray array];
        self.arrayRow     = [NSMutableArray array];
        self.dictionary   = [NSMutableDictionary dictionary];
        
        self.stringId = [NSString string];
        
//        self.chiArray = [NSMutableArray array];
        self.chiArrayRow = [NSMutableArray array];
        self.chiArraySection = [NSMutableArray array];
        self.chiDictionary = [NSMutableDictionary dictionary];
        self.searchArray = [NSMutableArray array];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self startConnection];
    [self setupViews];
    [self setupRefresh];
}
- (void)setupViews
{
    
    self.indexBar = [[BATableView alloc] initWithFrame:self.bounds];
    [self addSubview:self.indexBar];
    self.indexBar.delegate = self;
    self.indexBar.childrenTableView.delegate = self;
    self.indexBar.childrenTableView.dataSource = self;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, (self.frame.size.height - 60) / 2, 15, 60);
    [button setBackgroundImage:[UIImage imageNamed:@"side.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(scrollViewWillBeginDragging:) forControlEvents:UIControlEventTouchUpInside];
    [self.indexBar.childrenView addSubview:button];
    [_indexBar release];
    
}

- (void)startConnection
{
    [Connection networkHandlerWith:@"http://mrobot.pcauto.com.cn/v2/price/brands?v=4.0.0" block:^(id result) {
        NSMutableArray *arr = [result objectForKey:@"sections"];
        [arr removeObjectAtIndex:0];
        self.array = arr;
        for (NSMutableDictionary *dic in self.array) {
            [self.arraySection addObject:[dic objectForKey:@"index"]];
        }
        for (int i = 0; i < self.arraySection.count; i++) {
            self.arrayRow = [NSMutableArray array];
            for (NSMutableDictionary *dic1 in [[self.array objectAtIndex:i] objectForKey:@"brands"]) {
                Car *car = [[Car alloc] init];
                [car setValuesForKeysWithDictionary:dic1];
                car.Id   = [dic1 objectForKey:@"id"];
                car.name = [dic1 objectForKey:@"name"];
                car.logo = [dic1 objectForKey:@"logo"];
                [self.arrayRow addObject:car];
                // 把Model类存到本地数组searchArray中
                [self.searchArray addObject:car];
            }
            [self.dictionary setValue:self.arrayRow forKey:self.arraySection[i]];
        }
        [self.indexBar reloadData];
        
        // 写入本地
        static int flag = 1;
        if (flag == 1) {
            [self locationStore];
            flag = 0;
        }
        
        
    }];
}

- (void)startDetailConnection
{
    // 品牌找车中，点击每个品牌弹出的其子类，根据每个品牌的Id拼接其子类的接口
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/getSerialListByBrandId/%@", self.stringId];
    [Connection networkHandlerWith:str block:^(id result) {
       
        NSMutableArray *array = [result objectForKey:@"manufacturers"];
        // 初始化区数组
        self.chiArraySection = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            // 把区的名字存到区数组中
            NSString *str = [dic objectForKey:@"name"];
            [self.chiArraySection addObject:str];
            // 遍历子类数组，存到chiArrayRow数组中
            NSMutableArray *arr = [dic objectForKey:@"serials"];
            self.chiArrayRow = [NSMutableArray array];
            for (NSDictionary *dic1 in arr) {
                Car *car = [[Car alloc] init];
                // kvc赋值
                [car setValuesForKeysWithDictionary:dic1];
                // 把Model类存到chiArrayRow数组中
                [self.chiArrayRow addObject:car];
                [car release];
                
            }
            // 把区名当做key值，子类数组当做value值，存入chiDictionary字典中
            [self.chiDictionary setValue:self.chiArrayRow forKey:str];
        }
        // 刷新页面
        [self.indexBar.childrenTableView reloadData];
        
    }];
    
    // 2秒后刷新表格
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //刷新表格
        [self.indexBar.childrenTableView reloadData];
        //调用endRefreshing可以结束刷新状态
        [self.indexBar.childrenTableView footerEndRefreshing];
        _countx += 1;
    });
}

// 本地存储
- (void)locationStore
{
    // 找到沙盒的路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", paths);
    
    // 获取documents的路径
    NSString *documentPath = [paths objectAtIndex:0];
    
    // 归档类，将一个实现了NSCoding协议的对象，写入本地
    NSString *carPath = [documentPath stringByAppendingPathComponent:@"searchCar.aaa"];
    //    BOOL carResult = [self.SearchArray writeToFile:carPath atomically:YES];
    BOOL carResult = [NSKeyedArchiver archiveRootObject:self.searchArray toFile:carPath];
    NSLog(@"找车写入本地：%d", carResult);
}



#pragma mark BATableView
- (NSArray *)sectionIndexTitlesForABELTableView:(BATableView *)tableView
{
    return self.arraySection;
}

#pragma mark 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.indexBar.tableView) {
        return self.arraySection.count;
    } else {
        return self.chiArraySection.count;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.indexBar.tableView) {
        return self.arraySection[section];
    } else {
        return self.chiArraySection[section];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (tableView == self.indexBar.tableView) {
        NSMutableArray *arr = [self.dictionary objectForKey:[self.arraySection objectAtIndex:(section)]];
        return arr.count;
    } else {
        NSMutableArray *arr2 = [self.chiDictionary objectForKey:[self.chiArraySection objectAtIndex:section]];
        return arr2.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.indexBar.childrenTableView) {
        SeekBrandDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseseek"];
        if (!cell) {
            cell = [[[SeekBrandDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseseek"] autorelease];
        }
        NSMutableArray *arr = [self.chiDictionary objectForKey:[self.chiArraySection objectAtIndex:(indexPath.section)]];
        Car *car = arr[indexPath.row];
        cell.car = car;
        return cell;
    } else {
        SeekBrandBaseViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse1"];
        if (cell == nil) {
            cell = [[[SeekBrandBaseViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse1"] autorelease];
        }
        NSMutableArray *arr = [self.dictionary objectForKey:[self.arraySection objectAtIndex:(indexPath.section)]];
        Car *car = arr[indexPath.row];
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:car.logo]];
        cell.label.text = car.name;
        return cell;        
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 取消选择印记
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.indexBar.tableView) {
        // 执行动画 使放在一边的view移过来
        [UIView animateWithDuration:1 animations:^{
            self.indexBar.childrenView.frame = CGRectMake(70, 0, self.frame.size.width - 70, self.frame.size.height);
        }];
        NSString *str = [self.arraySection objectAtIndex:indexPath.section];
        Car *car = [[self.dictionary objectForKey:str] objectAtIndex:indexPath.row];
        self.stringId = car.Id;
        [self startDetailConnection];
    } else if (tableView == self.indexBar.childrenTableView) {
        
        Car *car1 = [[self.chiDictionary objectForKey:[self.chiArraySection objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        NSString *Idurl = [NSString stringWithFormat:@"http://price.pcauto.com.cn/sg%@/", car1.Id];
        NSLog(@"ID:%@", car1.Id);
        NSLog(@"Name:%@", car1.name);
 
        // block
        self.block(car1, Idurl);
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView != self.indexBar.childrenTableView) {
        
        [UIView animateWithDuration:1 animations:^{
            self.indexBar.childrenView.frame = CGRectMake(320, 0, self.frame.size.width - 70, self.frame.size.height);
        }];
    }
    
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.indexBar.childrenTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.indexBar.childrenTableView  headerEndRefreshing];
    });
}
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.indexBar.childrenTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.indexBar.childrenTableView headerBeginRefreshing];
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
